package com.example.security6atguigu.config;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
//        Object principal = authentication.getPrincipal(); // 获取到用户身份信息
//        Object credentials = authentication.getCredentials(); // 获取到用户凭证信息[password]
//        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); // 获取到用户权限信息

        String localizedMessage = exception.getLocalizedMessage(); // 获取到异常信息
        HashMap result = new HashMap();
        result.put("code",401);
        result.put("message",localizedMessage);
        // 将结果转换成json字符串
        String json = JSON.toJSONString(result);
        // 返回json数据到前端
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print(json);
    }
}
